//
//  KeyboaydResponder.swift
//  WeiboDemo
//
//  Created by 姬向阳 on 2020/4/28.
//  Copyright © 2020 SUNNYJ. All rights reserved.
//

import SwiftUI

// 用于监听键盘事件
class KeyboardResponder: ObservableObject {
    // 键盘高度,变动时所有用到的View都会更新
    @Published var keyboardHeight : CGFloat = 0
    // 键盘是否显示
    var keyboardShow: Bool { keyboardHeight > 0 }
    
    init() {
        // 在默认通知中心添加观察者,监听键盘弹出
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIWindow.keyboardWillShowNotification, object: nil)
        // 监听键盘消失
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIWindow.keyboardWillHideNotification, object: nil)
    }
    
    // 键盘弹出调用函数
    @objc private func keyboardWillShow(_ notifacation: Notification){
        // 通过Notification获取到键盘的高度
        guard let frame = notifacation.userInfo?[UIWindow.keyboardFrameEndUserInfoKey] as? CGRect else {
            return
        }
        keyboardHeight = frame.height
    }
    
    // 键盘消失调用函数
    @objc private func keyboardWillHide(_ notifacation: Notification){
        // 键盘高度设置为0
        keyboardHeight = 0
    }
}
